package xjtu.zd.server.common;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class txtChanger {
    /*
           * txt文档转html
             filePath:txt原文件路径
             htmlPosition:转化后生成的html路径
    */
    public void txtToHtml(String filePath) {
        String htmlPosition = filePath.substring(0,filePath.length()-4)+".html";
        try {
            //String encoding = UTF8";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { // 判断文件是否存在
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
                // 考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                // 写文件
                FileOutputStream fos = new FileOutputStream(new File(htmlPosition));
                OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
                BufferedWriter bw = new BufferedWriter(osw);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    bw.write("<p>&nbsp&nbsp&nbsp"+lineTxt + "</p>");
                }
                bw.close();
                osw.close();
                fos.close();
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }

    /*
        filePath：对应章节的txt文件路径
     */
    public List<String> toParagraph(String filePath){
        List<String> context =new ArrayList<String>();
        try{
            File file = new File(filePath);
            if (file.isFile() && file.exists()){
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
                // 考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                int i=0;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    context.add(lineTxt);
                    i++;
                }
                read.close();
                return context;
            } else {
                System.out.println("找不到指定的文件");
                return null;
            }
        }catch (Exception e){
            System.out.println("读取文件内容出错");
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
